/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package listener;

import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Web application lifecycle listener.
 * @author sestari
 */
public class connezione implements ServletContextListener, ServletContextAttributeListener {
Connection con = null;
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        
          con = connec("ares.science.unitn.it",3306,"db_user15","user15","useRPass15");
    	  ServletContext sc = sce.getServletContext();
    	  sc.setAttribute("con", con);
        
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(connezione.class.getName()).log(Level.SEVERE, null, ex);
        }
         
    }

    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    public  static Connection connec(String host, int post, String dbName, String user, String passwd){
		Connection dbConnection = null;
		try
		{
			String dbString =null;
			Class.forName("com.mysql.jdbc.Driver").newInstance();		
			dbString = "jdbc:mysql://ares.science.unitn.it/db_user15";
			dbConnection = (Connection) DriverManager.getConnection(dbString,user,passwd);		
			
		}catch (Exception e) {
			 System.out.println("Erro create conection: " + e.getMessage());
		}
		return dbConnection;
	}
	
}
